package com.example.common.core.domain;


import com.example.common.core.enums.ResultCode;
import lombok.Getter;
import lombok.Setter;

@Setter
@Getter
public class Result<T> {
    //状态码
    private int code;
    //消息内容
    private String msg;
    //响应数据体
    private T data;

    //封装一些常用的方法，提高代码的可维护性
    //响应失败。无数据
    public static <T> Result<T> ok(){
        Result<T> result = new Result<>();
        result.setCode(ResultCode.SUCCESS.getCode());
        result.setMsg(ResultCode.SUCCESS.getMsg());
        result.setData(null);
        return result;
    }

    //响应成功，有数据
    public static <T> Result<T> ok(T data){
        Result<T> result = new Result<>();
        result.setCode(ResultCode.SUCCESS.getCode());
        result.setMsg(ResultCode.SUCCESS.getMsg());
        result.setData(data);
        return result;
    }

    //响应失败
    public static <T> Result<T> fail(ResultCode resultCode){
        Result<T> result = new Result<>();
        result.setCode(resultCode.getCode());
        result.setMsg(resultCode.getMsg());
        result.setData(null);
        return result;
    }

    public static <T> Result<T> fail(int code, String msg) {
        return assembleResult(code, msg, null);
    }
    private static <T> Result<T> assembleResult(int code, String msg, T data) {
        Result<T> r = new Result<>();
        r.setCode(code);
        r.setData(data);
        r.setMsg(msg);
        return r;
    }

    public static <T> Result<T> fail(){
        Result<T> r = new Result<>();
        r.setCode(ResultCode.FAILED.getCode());
        r.setData(null);
        r.setMsg(ResultCode.FAILED.getMsg());
        return r;
    }
}
